import NavBar from '@/components/Global/NavBar'
import styles from './index.module.less'
import dayjs from 'dayjs'
import classNames from 'classnames'
import { ClockCircleOutlined, UpCircleOutlined } from '@ant-design/icons'
import { SkeletonParagraphWrap, SkeletonTitleWrap } from '@/components/Common/Skeleton'
import { history } from 'umi'
import { useEffect, useState } from 'react'
import { fetchClassDetail, fetchClassEvaluates } from '../api'
import { Dialog, Empty, Toast } from 'antd-mobile'
import { stores } from '@/stores'
import type { ClassDetail, Evaluate } from './interface'
import { EvaluateCategory } from '../enum'
import { YesNo } from '@/constant/enum'
import { RoleEnum } from '@/role'

const ItemCard = (props: Evaluate) => {
    const historyQuery = history.location.query as { id: string }
    const groupId = historyQuery.id

    // 仅学员填写类报告显示提交人数
    const showCount = props.category === EvaluateCategory.Student

    /** 根据提交人数判断数量是否可以点击 */
    const countClickable = props.write_number < props.student_number

    const onCardClick = () => {
        if (
            props.write_number === 0 &&
            props.category === EvaluateCategory.CourseOpinion &&
            [RoleEnum.center, RoleEnum.province].includes(stores.userStore.getRoleInfo!.role_id)
        ) {
            Toast.show({
                icon: '!',
                content: '该机构暂未进行填写',
            })
            return
        }

        if (
            // props.category === EvaluateCategory.CourseOpinion &&
            // props.is_write === YesNo.Yes &&
            // stores.userStore.isCompany
            props.is_write === YesNo.Yes
        ) {
            history.push({
                pathname: '/qualityEvaluate/write',
                query: { groupId, evaluateId: String(props.evaluate_id), listId: String(props.id) },
            })
            return
        }

        history.push({
            pathname: '/qualityEvaluate/detail',
            query: { groupId, evaluateId: String(props.evaluate_id), listId: String(props.id) },
        })
    }

    const onCountClick = () => {
        if (!countClickable) return
        Dialog.alert({
            title: '未提交学员',
            content: props.not_submit_student,
            confirmText: '关闭',
            closeOnMaskClick: true,
        })
    }

    // 带提交数量的Header
    const CountHeader = () => {
        return (
            <div className={styles.itemCard_header}>
                <div className={styles.itemCard_header_title}>{props.evaluate_name}</div>
                <div className={styles.itemCard_header_status}>
                    <span
                        className={classNames({
                            [styles.clickable]: countClickable,
                            [styles.unClickable]: !countClickable,
                        })}
                        onClick={e => {
                            e.stopPropagation()
                            onCountClick()
                        }}
                    >
                        {props.write_number}
                    </span>
                    <span>{`/${props.student_number}`}</span>
                </div>
            </div>
        )
    }

    // 普通Header
    const NormalHeader = () => {
        return (
            <div className={styles.itemCard_header}>
                <div className={styles.itemCard_header_title}>{props.evaluate_name}</div>
            </div>
        )
    }

    return (
        <div
            className={classNames(styles.itemCard, {
                [styles.itemCard_count]: showCount,
                [styles.itemCard_normal]: !showCount,
            })}
            onClick={onCardClick}
        >
            {showCount ? <CountHeader /> : <NormalHeader />}

            <div className={styles.itemCard_content}>{props.lesson_name}</div>

            <div className={styles.itemCard_footer}>
                <div className={styles.splitLine} />
                <div className={styles.itemCard_footer_content}>
                    <div>
                        <ClockCircleOutlined className={styles.clockIcon} />
                        {dayjs(props.create_time).format('YYYY-MM-DD')}
                    </div>
                    <div className={styles.stepInIcon}>
                        <UpCircleOutlined />
                    </div>
                </div>
            </div>
        </div>
    )
}

export const QualityEvaluate = () => {
    const historyQuery = history.location.query as { id: string }

    const id = Number(historyQuery.id)

    const [loading, setLoading] = useState<boolean>(false)
    const [dataList, setDataList] = useState<Evaluate[]>([])
    const [detail, setDetail] = useState<ClassDetail>()
    // 是否可以发起评估（只有在未结班的情况下允许发起）
    const [publishable, setPublishable] = useState<boolean>(false)
    // 只有培训师可以发起评估
    const showPublishButton = stores.userStore.isTeacherRole && publishable

    useEffect(() => {
        const initDataList = async () => {
            const { data } = await fetchClassEvaluates(id)
            setDataList(data)
        }
        const initClassDetail = async () => {
            const { data } = await fetchClassDetail(id)
            setDetail(data)

            if (dayjs(new Date().toLocaleDateString()) > dayjs(data.end_date)) {
                // 已结班
                setPublishable(false)
            } else {
                // 未结班
                setPublishable(true)
            }
        }
        const initData = async () => {
            try {
                setLoading(true)
                await initDataList()
                await initClassDetail()
            } finally {
                setLoading(false)
            }
        }
        initData()
    }, [id])

    const onPublish = () => {
        history.push({ pathname: '/qualityEvaluate/publish', query: { id: String(id) } })
    }

    return (
        <div>
            <NavBar title="质量评估" />

            <div className={styles.page}>
                <SkeletonTitleWrap animated loading={loading}>
                    <div className={styles.className}>
                        {`${detail?.name || '-'} ${detail?.code || '-'}`}
                    </div>
                </SkeletonTitleWrap>

                <div className={styles.list}>
                    <SkeletonParagraphWrap animated lineCount={10} loading={loading}>
                        {dataList.map(item => {
                            return <ItemCard key={item.evaluate_id} {...item} />
                        })}

                        {dataList.length === 0 && <Empty description="暂无数据" />}
                    </SkeletonParagraphWrap>
                </div>
            </div>

            {showPublishButton && (
                <div className={styles.publishBtn} onClick={onPublish}>
                    <div className={styles.iconBg}>
                        <div />
                    </div>
                    <span>发起评估</span>
                </div>
            )}
        </div>
    )
}

export default QualityEvaluate
